<template>
  <div class="state-list">
    <!-- 工具栏 -->
    <div class="state-list-toolbar">
      <div class="toolbar-left">
        <a-select
          v-model:value="selectedModule"
          placeholder="选择模块"
          style="width: 160px"
          @change="handleModuleChange"
        >
          <a-select-option
            v-for="moduleType in moduleTypes"
            :key="moduleType.value"
            :value="moduleType.value"
          >
            {{ moduleType.label }}
          </a-select-option>
        </a-select>
        <a-input-search
          v-model:value="searchKeyword"
          placeholder="搜索状态"
          style="width: 200px"
          @search="handleSearch"
          allow-clear
        />
      </div>
      <div class="toolbar-right">
        <a-select
          v-model:value="statusFilter"
          placeholder="状态"
          style="width: 100px"
          @change="handleFilterChange"
        >
          <a-select-option value="all">全部</a-select-option>
          <a-select-option value="enabled">启用</a-select-option>
          <a-select-option value="disabled">禁用</a-select-option>
          <a-select-option value="visible">可见</a-select-option>
          <a-select-option value="hidden">隐藏</a-select-option>
        </a-select>
        <a-select
          v-model:value="sortBy"
          placeholder="排序"
          style="width: 110px"
          @change="handleSortChange"
        >
          <a-select-option value="sort_order">排序顺序</a-select-option>
          <a-select-option value="name">名称</a-select-option>
          <a-select-option value="created_at">创建时间</a-select-option>
          <a-select-option value="updated_at">更新时间</a-select-option>
        </a-select>
        <a-button
          type="primary"
          @click="handleCreateState"
          :disabled="!selectedModule"
        >
          <template #icon>
            <PlusOutlined />
          </template>
          新建状态
        </a-button>
      </div>
    </div>

    <!-- 统计信息 -->
    <div class="state-stats" v-if="filteredStates.length !== states.length || searchKeyword">
      <a-tag color="processing">
        显示 {{ filteredStates.length }} / {{ states.length }} 项
      </a-tag>
    </div>

    <!-- 批量操作工具栏 -->
    <div v-if="selectedIds.length > 0" class="batch-toolbar">
      <a-card :bordered="false" class="batch-card">
        <div class="batch-main">
          <div class="batch-info">
            <span class="count">{{ selectedIds.length }}</span>
            <span>项状态已选择</span>
          </div>
          <div class="batch-actions">
            <a-dropdown :trigger="['click']" :disabled="loading || batchLoading">
              <a-button type="primary" :loading="batchLoading">
                批量操作
                <template #icon>
                  <DownOutlined />
                </template>
              </a-button>
              <template #overlay>
                <a-menu @click="handleBatchCommand">
                  <a-menu-item key="delete" danger>
                    <template #icon>
                      <DeleteOutlined />
                    </template>
                    批量删除
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
            <a-button :disabled="loading || batchLoading" @click="clearSelection">
              取消选择
            </a-button>
          </div>
        </div>
      </a-card>
    </div>

    <!-- 全选工具栏 -->
    <div v-if="filteredStates.length > 0 && !selectedIds.length" class="select-all-toolbar">
      <a-checkbox 
        :checked="isAllSelected"
        :indeterminate="isIndeterminate"
        @change="handleSelectAll"
      >
        全选
      </a-checkbox>
    </div>

    <!-- 状态列表内容 -->
    <div class="state-list-content">
      <a-spin :spinning="loading">
        <div v-if="filteredStates && filteredStates.length > 0">
          <div class="state-items" ref="stateItemsRef">
            <div
              v-for="state in filteredStates"
              :key="state.id"
              :data-id="state.id"
              class="state-item"
              :class="{ 
                'state-item-disabled': !state.is_enabled,
                'state-item-hidden': !state.is_visible,
                'sortable-item': true,
                'state-item-selected': selectedIds.includes(state.id)
              }"
            >
              <div class="state-checkbox">
                <a-checkbox 
                  :checked="selectedIds.includes(state.id)"
                  @change="(e: any) => handleSelectionChange(state.id, e.target.checked)"
                />
              </div>
              <div class="state-info">
                <StateTag 
                  :state="state" 
                  :class="{
                    'disabled': !state.is_enabled,
                    'hidden': !state.is_visible
                  }"
                />
                <div class="state-details">
                  <div class="state-name-row">
                    <span class="state-name">{{ state.name }}</span>
                    <span class="state-code">{{ state.code }}</span>
                  </div>
                  <div v-if="state.description" class="state-description">
                    {{ state.description }}
                  </div>
                </div>
              </div>
              <div class="state-meta">
                <div class="state-flags">
                  <a-tag :color="getModuleColor(state.module_type)" size="small">
                    {{ getModuleLabel(state.module_type) }}
                  </a-tag>
                  <a-tag v-if="!state.is_enabled" color="error" size="small">禁用</a-tag>
                  <a-tag v-if="!state.is_visible" color="warning" size="small">隐藏</a-tag>
                  <a-tag v-if="state.is_default" color="success" size="small">默认</a-tag>
                </div>
                <div class="state-order">排序: {{ state.sort_order || 0 }}</div>
              </div>
              <div class="state-actions">
                <a-tooltip :title="state.is_enabled ? '禁用' : '启用'">
                  <a-button
                    type="text"
                    size="small"
                    class="action-btn"
                    :class="{ 'enabled': state.is_enabled }"
                    @click.stop="handleToggleEnabled(state)"
                    :loading="togglingStates.has(state.id)"
                  >
                    <template #icon>
                      <CheckOutlined v-if="state.is_enabled" />
                      <CloseOutlined v-else />
                    </template>
                  </a-button>
                </a-tooltip>
                <a-tooltip :title="state.is_default ? '取消默认' : '设为默认'">
                  <a-button
                    type="text"
                    size="small"
                    class="action-btn"
                    :class="{ 'is-default': state.is_default }"
                    @click.stop="handleSetDefault(state)"
                    :loading="togglingStates.has(state.id)"
                  >
                    <template #icon>
                      <StarOutlined />
                    </template>
                  </a-button>
                </a-tooltip>
                <a-tooltip title="编辑">
                  <a-button
                    type="text"
                    size="small"
                    class="action-btn"
                    @click="handleEditState(state)"
                  >
                    <template #icon>
                      <EditOutlined />
                    </template>
                  </a-button>
                </a-tooltip>
                <a-tooltip title="复制">
                  <a-button
                    type="text"
                    size="small"
                    class="action-btn"
                    @click="handleCopyState(state)"
                  >
                    <template #icon>
                      <CopyOutlined />
                    </template>
                  </a-button>
                </a-tooltip>
                <a-tooltip title="删除">
                  <a-button
                    type="text"
                    size="small"
                    danger
                    class="action-btn"
                    @click="handleDeleteState(state)"
                  >
                    <template #icon>
                      <DeleteOutlined />
                    </template>
                  </a-button>
                </a-tooltip>
              </div>
              <div class="state-drag-handle" title="拖动排序">
                <svg viewBox="0 0 20 20" width="16" height="16" fill="currentColor">
                  <circle cx="7" cy="5" r="1.5"></circle>
                  <circle cx="13" cy="5" r="1.5"></circle>
                  <circle cx="7" cy="10" r="1.5"></circle>
                  <circle cx="13" cy="10" r="1.5"></circle>
                  <circle cx="7" cy="15" r="1.5"></circle>
                  <circle cx="13" cy="15" r="1.5"></circle>
                </svg>
              </div>
            </div>
          </div>
          
          <!-- 分页组件 -->
          <div class="pagination-wrapper">
            <ConfigProvider :locale="zhCN">
              <a-pagination
                v-model:current="pagination.page"
                v-model:page-size="pagination.size"
                :total="pagination.total"
                :page-size-options="['10', '20', '50', '100']"
                :show-size-changer="true"
                :show-quick-jumper="true"
                :show-total="(total: number, range: [number, number]) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`"
                @change="handlePageChange"
                @show-size-change="handleSizeChange"
              />
            </ConfigProvider>
          </div>
        </div>
        <a-empty 
          v-else-if="!loading && filteredStates.length === 0 && states.length > 0" 
          description="没有符合条件的状态数据"
          :image="false"
        />
        <a-empty 
          v-else-if="!loading && states.length === 0" 
          description="暂无状态数据"
          :image="false"
        />
      </a-spin>
    </div>

    <!-- 状态编辑对话框 -->
    <StateEditDialog
      v-model:visible="editDialogVisible"
      :state="editingState"
      :module-type="selectedModule"
      @success="handleEditSuccess"
    />

    <!-- 状态创建对话框 -->
    <StateCreateDialog
      v-model:visible="createDialogVisible"
      :module-type="selectedModule"
      @success="handleCreateSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { message, Modal, ConfigProvider } from 'ant-design-vue'
import zhCN from 'ant-design-vue/locale/zh_CN'
import { PlusOutlined, EditOutlined, CopyOutlined, DeleteOutlined, CheckOutlined, CloseOutlined, DownOutlined, StarOutlined } from '@ant-design/icons-vue'
import type { StateResponse, ModuleType } from '@/types/state'
import { useStateStore } from '@/stores/state'
import { StateAPI } from '@/api/state'
import StateTag from './StateTag.vue'
import StateEditDialog from './StateEditDialog.vue'
import StateCreateDialog from './StateCreateDialog.vue'
import { MODULE_TYPES, getModuleLabel, getModuleColor } from '@/utils/moduleTypes'
import Sortable from 'sortablejs'

const stateStore = useStateStore()

// 使用统一的模块类型配置（必须在其他变量之前定义）
const moduleTypes = MODULE_TYPES

const loading = ref(false)
// 默认选择第一个模块（如果有模块列表）
const selectedModule = ref<ModuleType | null>(moduleTypes.length > 0 ? (moduleTypes[0].value as ModuleType) : null)
const searchKeyword = ref('')
const statusFilter = ref('all')
const sortBy = ref('sort_order')

// 分页状态
const pagination = ref({
  page: 1,
  size: 20,
  total: 0
})

// 对话框状态
const editDialogVisible = ref(false)
const editingState = ref<StateResponse | null>(null)
const createDialogVisible = ref(false)

// 拖拽相关
const stateItemsRef = ref<HTMLElement | null>(null)
const sortableInstance = ref<Sortable | null>(null)
const togglingStates = ref<Set<string>>(new Set())

// 批量操作相关
const selectedIds = ref<string[]>([])
const batchLoading = ref(false)

// 全选相关
const isAllSelected = computed(() => {
  return filteredStates.value.length > 0 && 
         filteredStates.value.every(state => selectedIds.value.includes(state.id))
})

const isIndeterminate = computed(() => {
  const selectedCount = filteredStates.value.filter(state => selectedIds.value.includes(state.id)).length
  return selectedCount > 0 && selectedCount < filteredStates.value.length
})

const handleSelectAll = (e: any) => {
  if (e.target.checked) {
    // 全选当前页面的所有状态
    filteredStates.value.forEach(state => {
      if (!selectedIds.value.includes(state.id)) {
        selectedIds.value.push(state.id)
      }
    })
  } else {
    // 取消全选
    const currentPageIds = filteredStates.value.map(s => s.id)
    selectedIds.value = selectedIds.value.filter(id => !currentPageIds.includes(id))
  }
}

// 从store获取状态数据
const states = computed(() => stateStore.states)

// 计算属性
const filteredStates = computed(() => {
  let result = states.value

  // 模块过滤（已移除"全部模块"选项，始终需要选择模块）
  if (selectedModule.value) {
    result = result.filter(state => state.module_type === selectedModule.value)
  }

  // 搜索过滤
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(state => 
      state.name.toLowerCase().includes(keyword) ||
      state.code.toLowerCase().includes(keyword) ||
      (state.description && state.description.toLowerCase().includes(keyword))
    )
  }

  // 状态过滤
  if (statusFilter.value !== 'all') {
    switch (statusFilter.value) {
      case 'enabled':
        result = result.filter(state => state.is_enabled)
        break
      case 'disabled':
        result = result.filter(state => !state.is_enabled)
        break
      case 'visible':
        result = result.filter(state => state.is_visible)
        break
      case 'hidden':
        result = result.filter(state => !state.is_visible)
        break
    }
  }

  // 排序
  result.sort((a, b) => {
    switch (sortBy.value) {
      case 'name':
        return a.name.localeCompare(b.name)
      case 'created_at':
        const aCreated = a.created_at ? new Date(a.created_at).getTime() : 0
        const bCreated = b.created_at ? new Date(b.created_at).getTime() : 0
        return bCreated - aCreated
      case 'updated_at':
        const aUpdated = a.updated_at ? new Date(a.updated_at).getTime() : 0
        const bUpdated = b.updated_at ? new Date(b.updated_at).getTime() : 0
        return bUpdated - aUpdated
      case 'sort_order':
      default:
        return (a.sort_order || 0) - (b.sort_order || 0)
    }
  })

  // 更新分页总数
  pagination.value.total = result.length

  // 分页处理
  const start = (pagination.value.page - 1) * pagination.value.size
  const end = start + pagination.value.size
  return result.slice(start, end)
})

// 事件处理
const handleModuleChange = (value: any) => {
  if (value === undefined || value === null) {
    // 如果清空，默认选择第一个模块（不允许清空）
    if (moduleTypes.length > 0) {
      selectedModule.value = moduleTypes[0].value as ModuleType
    }
    return
  }
  // 处理数组情况（多选模式）
  if (Array.isArray(value)) {
    return
  }
  const stringValue = String(value)
  // 只允许选择有效的模块类型
  if (MODULE_TYPES.some(mt => mt.value === stringValue)) {
    selectedModule.value = stringValue as ModuleType
    pagination.value.page = 1
  } else {
    // 如果值无效，默认选择第一个模块
    if (moduleTypes.length > 0) {
      selectedModule.value = moduleTypes[0].value as ModuleType
    }
  }
}

const handleSearch = () => {
  pagination.value.page = 1
}

const handleFilterChange = () => {
  pagination.value.page = 1
}

const handleSortChange = () => {
  pagination.value.page = 1
}

const handlePageChange = (page: number) => {
  pagination.value.page = page
}

const handleSizeChange = (_current: number, size: number) => {
  pagination.value.size = size
  pagination.value.page = 1
}

const handleCreateState = () => {
  if (!selectedModule.value) {
    message.warning('请先选择一个模块')
    return
  }
  createDialogVisible.value = true
}

const handleEditState = (state: StateResponse) => {
  editingState.value = state
  editDialogVisible.value = true
}

const handleCopyState = async (state: StateResponse) => {
  try {
    const copyData = {
      name: `${state.name} (副本)`,
      code: `${state.code}_copy`,
      module_type: state.module_type,
      description: state.description,
      color: state.color,
      icon: state.icon,
      sort_order: (state.sort_order || 0) + 1,
      is_enabled: state.is_enabled,
      is_visible: state.is_visible,
      is_default: false
    }
    
    await stateStore.createState(copyData)
    message.success('状态复制成功')
    await loadStates()
  } catch (error) {
    console.error('复制状态失败:', error)
    message.error('复制状态失败')
  }
}

const handleDeleteState = async (state: StateResponse) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除状态"${state.name}"吗？此操作不可恢复。`,
    okText: '确定',
    cancelText: '取消',
    okType: 'danger',
    onOk: async () => {
      try {
        const response = await StateAPI.deleteState(state.id, false)
        // 检查是否有警告信息（表示状态下有数据）
        const warning = response?.data?.warning
        if (warning) {
          message.warning(`${response?.data?.message || '状态删除成功'}（${warning}）`)
        } else {
          message.success(response?.data?.message || '状态删除成功')
        }
        await loadStates()
      } catch (error: any) {
        console.error('删除状态失败:', error)
        const errorMessage = error?.response?.data?.message || error?.message || '删除状态失败'
        message.error(errorMessage)
      }
    }
  })
}

const handleEditSuccess = () => {
  editDialogVisible.value = false
  editingState.value = null
  loadStates()
  message.success('状态更新成功')
}

const handleCreateSuccess = () => {
  createDialogVisible.value = false
  loadStates()
  message.success('状态创建成功')
}

// 切换启用/禁用状态
const handleToggleEnabled = async (state: StateResponse) => {
  togglingStates.value.add(state.id)
  try {
    const updateData = {
      is_enabled: !state.is_enabled
    }
    await stateStore.updateState(state.id, updateData)
    message.success(`状态已${updateData.is_enabled ? '启用' : '禁用'}`)
    await loadStates()
  } catch (error: any) {
    console.error('切换状态失败:', error)
    // 从错误中提取消息
    const errorMessage = error?.response?.data?.message || error?.message || '切换状态失败'
    // 如果错误消息包含"无法禁用"或"存在数据"等关键词，显示警告消息
    if (errorMessage.includes('无法禁用') || errorMessage.includes('存在') || errorMessage.includes('数据')) {
      message.warning(errorMessage)
    } else {
      message.error(errorMessage)
    }
  } finally {
    togglingStates.value.delete(state.id)
  }
}

// 设置/取消默认状态
const handleSetDefault = async (state: StateResponse) => {
  const isSettingDefault = !state.is_default
  
  Modal.confirm({
    title: isSettingDefault ? '设为默认状态' : '取消默认状态',
    content: isSettingDefault 
      ? `确定要将状态"${state.name}"设为默认状态吗？该模块的其他状态将自动取消默认。`
      : `确定要取消状态"${state.name}"的默认状态吗？`,
    okText: '确定',
    cancelText: '取消',
    onOk: async () => {
      togglingStates.value.add(state.id)
      try {
        const updateData = {
          is_default: isSettingDefault
        }
        await stateStore.updateState(state.id, updateData)
        message.success(isSettingDefault ? '已设为默认状态' : '已取消默认状态')
        await loadStates()
      } catch (error: any) {
        console.error('操作失败:', error)
        const errorMessage = error?.response?.data?.message || error?.message || '操作失败'
        message.error(errorMessage)
      } finally {
        togglingStates.value.delete(state.id)
      }
    }
  })
}

// 初始化拖拽排序
const initSortable = () => {
  if (!stateItemsRef.value || sortBy.value !== 'sort_order') {
    // 只在按排序顺序排序时启用拖拽
    // 清理之前的实例
    if (sortableInstance.value) {
      sortableInstance.value.destroy()
      sortableInstance.value = null
    }
    return
  }
  
  // 清理之前的实例
  if (sortableInstance.value) {
    sortableInstance.value.destroy()
    sortableInstance.value = null
  }
  
  // 只在选择了特定模块时启用拖拽（避免跨模块拖拽）
  if (!selectedModule.value) {
    return
  }
  
  nextTick(() => {
    if (!stateItemsRef.value) return
    
    sortableInstance.value = new Sortable(stateItemsRef.value, {
      animation: 150,
      handle: '.state-drag-handle',
      ghostClass: 'sortable-ghost',
      chosenClass: 'sortable-chosen',
      dragClass: 'sortable-drag',
      onEnd: async (evt) => {
        const { oldIndex, newIndex } = evt
        if (oldIndex === undefined || newIndex === undefined || oldIndex === newIndex) {
          return
        }
        
        // 获取当前过滤后的状态列表（需要获取完整的当前模块状态）
        const currentStates = [...filteredStates.value]
        if (!currentStates || currentStates.length === 0) return
        
        // 计算实际的排序顺序（考虑分页）
        const pageStart = (pagination.value.page - 1) * pagination.value.size
        const actualOldIndex = pageStart + oldIndex
        const actualNewIndex = pageStart + newIndex
        
        // 获取当前模块的所有状态（用于计算完整排序）
        const moduleStates = states.value
          .filter(s => s.module_type === selectedModule.value)
          .sort((a, b) => (a.sort_order || 0) - (b.sort_order || 0))
        
        // 重新排序
        const movedState = moduleStates[actualOldIndex]
        moduleStates.splice(actualOldIndex, 1)
        moduleStates.splice(actualNewIndex, 0, movedState)
        
        // 生成新的排序顺序（从1开始）
        const updates = moduleStates.map((state, index) => ({
          id: state.id,
          sort_order: index + 1
        }))
        
        try {
          loading.value = true
          await StateAPI.batchUpdateSortOrder(updates)
          message.success('排序更新成功')
          await loadStates()
        } catch (error) {
          console.error('更新排序失败:', error)
          message.error('更新排序失败，已恢复原顺序')
          // 恢复原顺序
          await loadStates()
        } finally {
          loading.value = false
        }
      }
    })
  })
}

// 批量操作相关
const handleSelectionChange = (stateId: string, checked: boolean) => {
  if (checked) {
    if (!selectedIds.value.includes(stateId)) {
      selectedIds.value.push(stateId)
    }
  } else {
    const index = selectedIds.value.indexOf(stateId)
    if (index > -1) {
      selectedIds.value.splice(index, 1)
    }
  }
}

const clearSelection = () => {
  selectedIds.value = []
}

const handleBatchCommand = (info: { key: string | number }) => {
  const key = String(info.key)
  switch (key) {
    case 'delete':
      handleBatchDelete()
      break
    default:
      break
  }
}

const handleBatchDelete = () => {
  if (selectedIds.value.length === 0) {
    message.warning('请选择要删除的状态')
    return
  }

  Modal.confirm({
    title: '确认批量删除',
    content: `确定要删除选中的 ${selectedIds.value.length} 个状态吗？此操作不可恢复。`,
    okText: '确认删除',
    okType: 'danger',
    cancelText: '取消',
    onOk: async () => {
      await executeBatchDelete(false)
    }
  })
}

const executeBatchDelete = async (force: boolean = false) => {
  if (selectedIds.value.length === 0) return

  batchLoading.value = true
  try {
    const result = await StateAPI.batchDeleteStates(selectedIds.value.slice(), force)
    
    if (!result) {
      message.error('批量删除状态失败：响应数据为空')
      return
    }
    
    // 显示成功消息
    if (result.deleted_count > 0) {
      // 检查是否有警告信息（表示有状态下有数据）
      const hasWarnings = result.errors?.some(e => e.includes('已强制删除'))
      if (hasWarnings) {
        // 提取警告信息
        const warnings = result.errors?.filter(e => e.includes('已强制删除')) || []
        const warningText = warnings.slice(0, 3).join('；')
        const moreWarnings = warnings.length > 3 ? ` 等共 ${warnings.length} 个状态有数据` : ''
        message.warning(`成功删除 ${result.deleted_count} 个状态（${warningText}${moreWarnings}）`)
      } else {
        message.success(`成功删除 ${result.deleted_count} 个状态`)
      }
    }
    
    // 显示其他错误信息（非警告类的错误）
    if (result.skipped_count > 0) {
      if (result.errors && result.errors.length > 0) {
        // 过滤出非警告的错误（不包含"已强制删除"的错误）
        const realErrors = result.errors.filter(e => !e.includes('已强制删除'))
        
        if (realErrors.length > 0) {
          const errorPreview = realErrors.slice(0, 3)
          let errorText = errorPreview.join('；')
          if (errorText.length > 100) {
            errorText = errorText.substring(0, 100) + '...'
          }
          const moreInfo = realErrors.length > 3 ? ` 等共 ${realErrors.length} 个错误` : ''
          message.warning(`部分状态删除失败：${errorText}${moreInfo}`)
        }
      } else {
        message.warning(`跳过 ${result.skipped_count} 个状态`)
      }
    }
    
    // 如果没有删除任何状态，显示提示
    if (result.deleted_count === 0 && result.skipped_count > 0) {
      const hasOnlyWarnings = result.errors?.every(e => e.includes('已强制删除'))
      if (!hasOnlyWarnings) {
        message.warning('没有状态被删除，请检查错误信息')
      }
    }
    
    // 清除选择
    clearSelection()
    
    // 重新加载状态列表
    await loadStates()
  } catch (error: any) {
    console.error('批量删除状态失败:', error)
    // 从错误响应中提取消息
    let errorMessage = '批量删除状态失败'
    if (error?.response?.data) {
      const errorData = error.response.data
      if (errorData.message) {
        errorMessage = errorData.message
      } else if (errorData.error?.message) {
        errorMessage = errorData.error.message
      }
    } else if (error?.message) {
      errorMessage = error.message
    }
    message.error(errorMessage)
  } finally {
    batchLoading.value = false
  }
}

// 加载状态数据
const loadStates = async () => {
  loading.value = true
  try {
    await stateStore.fetchStates()
    // 加载完成后重新初始化拖拽
    nextTick(() => {
      initSortable()
    })
  } catch (error) {
    console.error('加载状态失败:', error)
    message.error('加载状态失败')
  } finally {
    loading.value = false
  }
}

// 设置模块过滤器（供父组件调用）
const setModuleFilter = (moduleType: ModuleType | null) => {
  if (moduleType) {
    selectedModule.value = moduleType
  } else if (moduleTypes.length > 0) {
    // 如果没有指定模块，默认选择第一个
    selectedModule.value = moduleTypes[0].value as ModuleType
  } else {
    selectedModule.value = null
  }
  pagination.value.page = 1
}


// 暴露方法给父组件
defineExpose({
  loadStates,
  setModuleFilter
})

// 监听模块变化
watch(selectedModule, () => {
  pagination.value.page = 1
  nextTick(() => {
    initSortable()
  })
})

// 监听排序方式变化
watch(sortBy, () => {
  nextTick(() => {
    initSortable()
  })
})

// 监听过滤后的状态列表变化
watch(() => filteredStates.value.length, () => {
  nextTick(() => {
    initSortable()
  })
})

// 监听过滤后的状态列表变化，清除不在列表中的选择
watch(() => filteredStates.value.map(s => s.id), (currentIds) => {
  selectedIds.value = selectedIds.value.filter(id => currentIds.includes(id))
}, { deep: true })

// 组件卸载时清理拖拽实例
onUnmounted(() => {
  if (sortableInstance.value) {
    sortableInstance.value.destroy()
    sortableInstance.value = null
  }
})

onMounted(() => {
  loadStates()
  nextTick(() => {
    initSortable()
  })
})
</script>

<style scoped>
.state-list {
  display: flex;
  flex-direction: column;
  width: 100%;
}

/* 工具栏 */
.state-list-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  gap: 12px;
  flex-wrap: wrap;
}

.toolbar-left,
.toolbar-right {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

/* 统计信息 */
.state-stats {
  margin-bottom: 16px;
}

/* 批量操作工具栏 */
.batch-toolbar {
  margin-bottom: 16px;
}

.batch-card {
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  background: linear-gradient(135deg, rgba(79, 111, 236, 0.1) 0%, rgba(105, 162, 255, 0.1) 100%);
}

.batch-main {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.batch-info {
  font-weight: 600;
  color: #2c3a5f;
  display: flex;
  align-items: center;
  gap: 4px;
  
  .count {
    font-size: 16px;
    color: #1890ff;
    font-weight: 700;
  }
  
  > span:not(.count) {
    font-size: 13px;
    color: #606266;
  }
}

.batch-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.state-item-selected {
  border-color: #1890ff;
  background: #f0f8ff;
}

.state-checkbox {
  margin-right: 12px;
  flex-shrink: 0;
}

.select-all-toolbar {
  margin-bottom: 12px;
  padding: 8px 0;
}

/* 状态列表内容 */
.state-list-content {
  flex: 1;
}

.state-items {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 24px;
}

.state-item {
  display: flex;
  align-items: center;
  padding: 16px;
  background: #fff;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}

.state-item:hover {
  border-color: #d9d9d9;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transform: translateY(-1px);
}

.state-item-disabled {
  opacity: 0.65;
  background: #fafafa;
}

.state-item-hidden {
  border-style: dashed;
  opacity: 0.8;
}

.state-info {
  display: flex;
  align-items: flex-start;
  flex: 1;
  gap: 12px;
  min-width: 0;
}

.state-details {
  flex: 1;
  min-width: 0;
}

.state-name-row {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 6px;
}

.state-name {
  font-weight: 500;
  color: #262626;
  font-size: 14px;
}

.state-code {
  font-size: 12px;
  color: #8c8c8c;
  font-family: 'Monaco', 'Menlo', 'Consolas', monospace;
  background: #f5f5f5;
  padding: 2px 6px;
  border-radius: 3px;
}

.state-description {
  font-size: 12px;
  color: #8c8c8c;
  line-height: 1.5;
  margin-top: 4px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.state-meta {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 8px;
  margin-right: 12px;
  min-width: 120px;
}

.state-flags {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
  justify-content: flex-end;
}

.state-order {
  font-size: 12px;
  color: #8c8c8c;
  white-space: nowrap;
}

.state-actions {
  display: flex;
  align-items: center;
  gap: 0;
  opacity: 0;
  transition: opacity 0.2s;
}

.state-item:hover .state-actions {
  opacity: 1;
}

.action-btn {
  color: #8c8c8c;
  transition: color 0.2s;
}

.action-btn:hover {
  color: #1890ff;
}

.action-btn.danger:hover {
  color: #ff4d4f;
}

.action-btn.enabled {
  color: #52c41a;
}

.action-btn.enabled:hover {
  color: #73d13d;
}

.action-btn.is-default {
  color: #faad14;
}

.action-btn.is-default:hover {
  color: #ffc53d;
}

/* 拖拽手柄 */
.state-drag-handle {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  margin-left: 8px;
  color: #d9d9d9;
  cursor: move;
  opacity: 0;
  transition: all 0.2s;
}

.state-item:hover .state-drag-handle {
  opacity: 1;
}

.state-drag-handle:hover {
  color: #1890ff;
}

.state-drag-handle svg {
  display: block;
}

/* 拖拽样式 */
.sortable-ghost {
  opacity: 0.4;
  background: #f5f5f5;
}

.sortable-chosen {
  cursor: grabbing;
}

.sortable-drag {
  opacity: 0.8;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.sortable-item {
  cursor: default;
}

/* 分页 */
.pagination-wrapper {
  display: flex;
  justify-content: center;
  padding: 20px 0;
  border-top: 1px solid #f0f0f0;
  margin-top: 8px;
}

/* 响应式 */
@media (max-width: 768px) {
  .state-list-toolbar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .toolbar-left,
  .toolbar-right {
    width: 100%;
    justify-content: space-between;
  }
  
  .state-item {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
  
  .state-info {
    width: 100%;
  }
  
  .state-meta {
    align-items: flex-start;
    margin-right: 0;
    width: 100%;
    flex-direction: row;
    justify-content: space-between;
  }
  
  .state-actions {
    opacity: 1;
    width: 100%;
    justify-content: flex-end;
    padding-top: 8px;
    border-top: 1px solid #f0f0f0;
  }
}
</style>